import { login, logout, getInfo } from '@/api/acl/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter , allAsyncRoutes , constantRoutes, anyRoute} from '@/router'
import router from '@/router'
//引入loadsh深度clone
import cloneDeep from 'lodash/cloneDeep'


//深度过滤没有的路由
function filterAsyncRoutes(allAsyncRoutes,routeNames){
  //根据返回的路由权限信息,返回所有的适合当前用户访问路由
  let asyncRoutes  = allAsyncRoutes.filter(item=>{
    if(routeNames.indexOf(item.name) !== -1){
      //没找到该路由的话,开始找其子路由
      if(item.children && item.children.length){
        //再次递归调用该函数,将子路由覆盖,知道不在包含子路由位置
        item.children = filterAsyncRoutes(item.children,routeNames)
      }
      //将匹配完成的全部返回
      return true
    }
  })
  return asyncRoutes
}

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    asyncRoutes:[],//存储路由信息
    routes:[],//存放所有关于该用户可以访问的路由
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROUTES(state,asyncRoutes){
    //将匹配完毕的数组暂存
    state.asyncRoutes = asyncRoutes
    //将基本路由和异步路由合并
    state.routes = constantRoutes.concat(asyncRoutes,anyRoute)
    //动态将路由添加
    router.addRoutes([...asyncRoutes,anyRoute])
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar} = data
        //路由重新定义,匹配自己拥有的
        const routes = ["authority","permissionList","userList","roleList",
                        "commodityType","commodity","attribute","Attributelist",
                        "editer","EditerAttribute","property","Property",
                        'SPU','Spu','SKU','Sku','AddList','EditList','recommend','Recommend',""]
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_ROUTES',filterAsyncRoutes(cloneDeep(allAsyncRoutes),routes))
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

